{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "db29ba85",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    },
    "tags": []
   },
   "source": [
    "\n",
    "# Demo: Solving 3-SAT Using Grover's Algorithm\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Grover's algorithm [[1](#Gro97),[2](#GroWiki)] is a quantum search algorithm that enables searching a dataset of $N$ items using $O(\\sqrt{N})$ queries, in contrast to classical algorithms which require $\\Omega(N)$ queries in the worst case. Using the algorithm allows us to speed-up various computations that are considered classically intractable.\n",
    "For example, the 3-SAT problem [[3](#3SAT)] is a famous $\\text{NP-Complete}$ problem, a solution of which allows solving any problem in the complexity class $\\text{NP}$.\n",
    "\n",
    "In this demo, we will show how the Classiq platform enables us to solve an instance of 3-SAT using Grover's algorithm at a higher functional level, avoiding the implementation details one is usually exposed to when using other platforms.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b14dbae",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## The 3-SAT Formula\n",
    "\n",
    "We now specify the 3-CNF [[4](#CNF)] formula that we wish to find a solution for:\n",
    "$$ (x_1 \\lor x_2 \\lor x_3) \\land (\\neg x_1 \\lor x_2 \\lor x_3) \\land (\\neg x_1 \\lor \\neg x_2 \\lor \\neg x_3) \\land (\\neg x_1 \\lor \\neg x_2 \\lor x_3) \\land (x_1 \\lor x_2 \\lor \\neg x_3) \\land (\\neg x_1 \\lor x_2 \\lor \\neg x_3) $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dda1a10d-406f-45f2-9431-13df855375de",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:28.349039Z",
     "iopub.status.busy": "2024-05-07T14:30:28.348545Z",
     "iopub.status.idle": "2024-05-07T14:30:28.359501Z",
     "shell.execute_reply": "2024-05-07T14:30:28.358822Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "formula = \"\"\"\n",
    "    ( ( x1) or ( x2) or ( x3) ) and\n",
    "    ( (not x1) or ( x2) or ( x3) ) and\n",
    "    ( (not x1) or (not x2) or (not x3) ) and\n",
    "    ( (not x1) or (not x2) or ( x3) ) and\n",
    "    ( ( x1) or ( x2) or (not x3) ) and\n",
    "    ( (not x1) or ( x2) or (not x3) )\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5563fbc5",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Using the package `truth-table-generator` [[5](#TTG)], we can see the formula above has 4 solutions (out of 8 possible assignments):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1c9c04c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:28.364188Z",
     "iopub.status.busy": "2024-05-07T14:30:28.363068Z",
     "iopub.status.idle": "2024-05-07T14:30:46.769206Z",
     "shell.execute_reply": "2024-05-07T14:30:46.768354Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "%%capture\n",
    "!pip install -q truth-table-generator==1.1.2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ba4ec235",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:46.774000Z",
     "iopub.status.busy": "2024-05-07T14:30:46.772901Z",
     "iopub.status.idle": "2024-05-07T14:30:47.420460Z",
     "shell.execute_reply": "2024-05-07T14:30:47.419771Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+------+------+------+------------------------------------------------+\n",
      "|  x1  |  x2  |  x3  |          ( ( x1) or ( x2) or ( x3) ) and       |\n",
      "|      |      |      |         ( (not x1) or ( x2) or ( x3) ) and     |\n",
      "|      |      |      |      ( (not x1) or (not x2) or (not x3) ) and  |\n",
      "|      |      |      |       ( (not x1) or (not x2) or ( x3) ) and    |\n",
      "|      |      |      |         ( ( x1) or ( x2) or (not x3) ) and     |\n",
      "|      |      |      |         ( (not x1) or ( x2) or (not x3) )      |\n",
      "|------+------+------+------------------------------------------------|\n",
      "|  1   |  1   |  1   |                       0                        |\n",
      "|  1   |  1   |  0   |                       0                        |\n",
      "|  1   |  0   |  1   |                       0                        |\n",
      "|  1   |  0   |  0   |                       0                        |\n",
      "|  0   |  1   |  1   |                       1                        |\n",
      "|  0   |  1   |  0   |                       1                        |\n",
      "|  0   |  0   |  1   |                       0                        |\n",
      "|  0   |  0   |  0   |                       0                        |\n",
      "+------+------+------+------------------------------------------------+\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    import ttg\n",
    "\n",
    "    print(ttg.Truths([\"x1\", \"x2\", \"x3\"], [formula[1:-1]]))\n",
    "except:\n",
    "    print(\"Please import 'truth-table-generator' in order to print the truth table\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54616eaa",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Note that since there are multiple satisfying assignments for the formula, the goal of the Grover quantum algorithm is to find one of them.\n",
    "This is contrast to the usual description of the search problem (found in [2](#GroWiki)), in which there is a single solution (out of $N$ possibilities).\n",
    "\n",
    "## Loading the Grover search model\n",
    "\n",
    "Next, we load the Grover search model which we use to find the solution. To specify the model, we need to define the oracle it uses. Each oracle call is analogous to a classical query. In this case, we define an oracle based on the 3-CNF formula defined earlier. Along with the standard definitions of the arithmetic expression for the oracle and the variable definitions, the oracle also requires us to specify the uncomputation method (in this case - \"optimized\").\n",
    "In addition, we define the number of grover operator repetitions in the model (which is based on the frequency of solutions in the search space), and the number of samples to take on this circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4848a14b-956c-4e2b-ad2e-c52e12d0b915",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:47.424975Z",
     "iopub.status.busy": "2024-05-07T14:30:47.423811Z",
     "iopub.status.idle": "2024-05-07T14:30:49.785161Z",
     "shell.execute_reply": "2024-05-07T14:30:49.784363Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "from classiq import RegisterUserInput, construct_grover_model\n",
    "\n",
    "register_size = RegisterUserInput(size=1)\n",
    "\n",
    "qmod = construct_grover_model(\n",
    "    num_reps=1,\n",
    "    expression=\"(\" + formula + \")\",\n",
    "    definitions=[\n",
    "        (\"x1\", register_size),\n",
    "        (\"x2\", register_size),\n",
    "        (\"x3\", register_size),\n",
    "    ],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "313452da-2e54-4fc0-b681-6c7bd8bdf6d1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:49.790614Z",
     "iopub.status.busy": "2024-05-07T14:30:49.789092Z",
     "iopub.status.idle": "2024-05-07T14:30:49.805199Z",
     "shell.execute_reply": "2024-05-07T14:30:49.804566Z"
    }
   },
   "outputs": [],
   "source": [
    "from classiq import write_qmod\n",
    "\n",
    "write_qmod(qmod, \"3_sat_grover\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb73f614",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Synthesizing the Circuit\n",
    "\n",
    "We proceed by synthesizing the circuit using Classiq's synthesis engine. The synthesis should take approximately several seconds:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "994f958c-595e-4a56-9e41-a5aaf8a75b03",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:49.809476Z",
     "iopub.status.busy": "2024-05-07T14:30:49.808430Z",
     "iopub.status.idle": "2024-05-07T14:30:52.379053Z",
     "shell.execute_reply": "2024-05-07T14:30:52.378371Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq import QuantumProgram, synthesize\n",
    "\n",
    "qprog = synthesize(qmod)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c161436b-4ee9-4e35-94cd-2831a893aaf6",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    },
    "tags": []
   },
   "source": [
    "## Showing the Resulting Circuit\n",
    "\n",
    "After Classiq's synthesis engine has finished the job, we can show the resulting circuit in the interactive GUI:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fd3eb709-e7ef-4d46-8f7a-e42c34ee9381",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:52.383704Z",
     "iopub.status.busy": "2024-05-07T14:30:52.382465Z",
     "iopub.status.idle": "2024-05-07T14:30:52.524572Z",
     "shell.execute_reply": "2024-05-07T14:30:52.523875Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/6b9562a5-c126-4489-8463-3fa4b21ef13a?version=0.41.0.dev39%2B79c8fd0855\n"
     ]
    }
   ],
   "source": [
    "circuit = QuantumProgram.from_qprog(qprog)\n",
    "circuit.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "27f74a0b-6cf0-4718-a05a-1b50aaf11825",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:52.529191Z",
     "iopub.status.busy": "2024-05-07T14:30:52.528004Z",
     "iopub.status.idle": "2024-05-07T14:30:52.534489Z",
     "shell.execute_reply": "2024-05-07T14:30:52.533831Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "429\n"
     ]
    }
   ],
   "source": [
    "print(circuit.transpiled_circuit.depth)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9900e10e",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Executing the circuit\n",
    "\n",
    "Lastly, we can execute the resulting circuit with Classiq's execute interface, using the `execute` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "79e9c4c7-5c29-4d4c-a01d-26a01b7805de",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:52.538864Z",
     "iopub.status.busy": "2024-05-07T14:30:52.537762Z",
     "iopub.status.idle": "2024-05-07T14:30:54.024976Z",
     "shell.execute_reply": "2024-05-07T14:30:54.024127Z"
    },
    "pycharm": {
     "name": "#%%\n"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq import execute, set_quantum_program_execution_preferences\n",
    "from classiq.execution import (\n",
    "    ClassiqBackendPreferences,\n",
    "    ClassiqSimulatorBackendNames,\n",
    "    ExecutionPreferences,\n",
    ")\n",
    "\n",
    "backend_preferences = ExecutionPreferences(\n",
    "    backend_preferences=ClassiqBackendPreferences(\n",
    "        backend_name=ClassiqSimulatorBackendNames.SIMULATOR\n",
    "    )\n",
    ")\n",
    "\n",
    "qprog = set_quantum_program_execution_preferences(qprog, backend_preferences)\n",
    "optimization_result = execute(qprog).result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "f037bbf6-1386-4141-8221-4496d47caf0a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:54.028682Z",
     "iopub.status.busy": "2024-05-07T14:30:54.028439Z",
     "iopub.status.idle": "2024-05-07T14:30:54.031993Z",
     "shell.execute_reply": "2024-05-07T14:30:54.031309Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "res = optimization_result[0].value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "478e4440",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Printing out the result, we see that our execution of Grover's algorithm successfully found the satisfying assignments for the input formula:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c0f1248c-9f10-4b88-b64f-317bf811ae1f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T14:30:54.036355Z",
     "iopub.status.busy": "2024-05-07T14:30:54.035257Z",
     "iopub.status.idle": "2024-05-07T14:30:54.046366Z",
     "shell.execute_reply": "2024-05-07T14:30:54.045758Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{('0', '1', '1'): 478, ('0', '1', '0'): 522}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.counts_of_multiple_outputs((\"x1\", \"x2\", \"x3\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49c24c5e",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "\n",
    "# References\n",
    "\n",
    "<a name='Gro97'>[1]</a>: [Grover, Lov K. \"Quantum mechanics helps in searching for a needle in a haystack.\" Physical review letters 79.2 (1997): 325.](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.79.325)\n",
    "\n",
    "<a name='GroWiki'>[2]</a>: [Grover's algorithm (Wikipedia)](https://en.wikipedia.org/wiki/Grover%27s_algorithm)\n",
    "\n",
    "<a name='3SAT'>[3]</a>: [3-SAT Problem (Wikipedia)](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#3-satisfiability)\n",
    "\n",
    "<a name='CNF'>[4]</a>: [Conjunctive Normal Form (Wikipedia)](https://en.wikipedia.org/wiki/Conjunctive_normal_form)\n",
    "\n",
    "<a name='TTG'>[5]</a>: [truth-table-generator (PyPI)](https://pypi.org/project/truth-table-generator)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "vscode": {
   "interpreter": {
    "hash": "a07aacdcc8a415e7643a2bc993226848ff70704ebef014f87460de9126b773d0"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
